package com.example.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class TCPService extends Service {
    public static Socket socket;
    public static PrintStream output;
    boolean conn = false;
    String ip="10.10.100.254";
    String port="8089";
    int recDtaLength=128;

    public TCPService()
    {

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        MyThread myThread = new MyThread();
        new Thread(myThread).start();
        ip=intent.getStringExtra("ipaddress");
        port=intent.getStringExtra("port");
        System.out.println("新的TCP连接，新的IP："+intent.getStringExtra("ipaddress")+"新的端口号："+intent.getStringExtra("port"));
        return super.onStartCommand(intent, flags, startId);
    }
    //socket连接线程
    class MyThread implements Runnable{
        @Override
        public void run(){
            try {
                socket = new Socket();
                SocketAddress socAddress = new InetSocketAddress(ip ,Integer.valueOf(port));
                socket.connect(socAddress, 5000);
                InputStream inputstream = socket.getInputStream();
                /* 获取输出流 */
                output = new PrintStream(socket.getOutputStream(), true, "utf-8");
                conn = true;
                byte buffer[] = new byte[recDtaLength];//接收数组的长度
                int len2 ;
                String receiveData;
                //非阻塞式连接
                while(conn){
                    //接收网络数据
                    if( (len2 = inputstream.read(buffer)) != -1){
                        receiveData = new String(buffer, 0, len2);
                        Intent CMDintent = new Intent();
                        CMDintent.setAction("com.example.communication.data");
                        //CMDintent.putExtra("data", buffer);//buffer为数组，receivedata为文本
                        CMDintent.putExtra("data", receiveData);//buffer为数组，receivedata为文本
                        sendBroadcast(CMDintent);
                    }else{
                        break;
                    }
                }
                output.close();
                socket.close();
                Looper.loop();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                // Looper.prepare();
            }
        }

    };

    //发送方法（（可以把参数改成Byte[]）：
    public static void send(final byte[] arr)
    {
        new Thread(new Runnable() {
            public void run() {
                if (socket.isConnected()) {
                    try {
                        output.write(arr);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}